//
//  WxLogin.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/11.
//

import Foundation
import SwiftUI
import GRDB

class LocalConfigImpl : ConfigProtocol {
    
    
    func getFolderConfig() async throws -> FolderConfig {
        let folderConfigs = try await DatabaseFolderManager.shared.dbQueue.read { db in
            try FolderConfig
                .limit(1)
                .fetchAll(db)
        }
        var config = folderConfigs.first
        if config == nil {
            config = FolderConfig()
            try await saveFolderConfig(bean: config!)
        }
        return config!
    }
    
    func saveFolderConfig(bean: FolderConfig) async throws {
        try await DatabaseFolderManager.shared.dbQueue.write { db in
            if bean.id == nil {
                try bean.insert(db)
            } else {
                try bean.update(db)
                showLog("保存数据")
            }
        }
    }
    
    func createMainFolderDB(folder : CloudFolderBean?) async throws {
        try check(folder != nil, "数据不能为空")
        if let folder = folder {
            //保存云目录
            let dbFolderMainId = UUID().uuidString
            folder.objectId = dbFolderMainId
            try await DatabaseFolderManager.shared.dbQueue.write { db in
                try folder.insert(db)
            }
            let config = try await getFolderConfig()
            config.dbFolderMainId = dbFolderMainId
            try await saveFolderConfig(bean: config)
        }
    }
    
    func clearRoleList() {
        //代理那边处理
    }
    
    func getAiRole(roleId: String?) async throws -> AiRoleBean {
        //代理那边处理
        AiRoleBean()
    }
    
    func getSelectAiRoleList() async throws -> [AiRoleBean] {
        //代理那边处理
        []
    }
    
    func getAiRoleList(_ force: Bool = false) async throws -> [AiRoleBean] {
        return try await DatabaseFolderManager.shared.dbQueue.read { db in
            try AiRoleBean
                .filter(Column("status") == IStatusType.NORMAL.rawValue)
                .order(Column("sort").desc)
                .fetchAll(db)
        }
    }
    
    func addAiRole(bean: AiRoleBean, isAdd: Bool) async throws -> AiRoleBean {
        let curTime = getMillisecond(try await getNetTime())
        try await DatabaseFolderManager.shared.dbQueue.write { db in
            bean.modifySign = true
            if isAdd {
                bean.createTime = curTime
                bean.updateTime = curTime
                bean.objectId = UUID().uuidString
                try bean.insert(db)
            } else {
                try bean.update(db)
                showLog("保存数据")
            }
        }
        return bean
    }
    
    func delAiRole(bean: AiRoleBean) async throws {
        try await DatabaseFolderManager.shared.dbQueue.write { db in
            try AiRoleBean
                .filter(Column("objectId") == bean.objectId)
                .deleteAll(db)
        }
    }
    
    func selectAiRole(list: [AiRoleBean]) async throws {
        let config = try await getFolderConfig()
        config.aiRoleList = list.map { $0.objectId ?? "" }
        config.modifySign = true
        try await saveFolderConfig(bean: config)
    }

    
    func getTagList() async throws -> [TagBean] {
        return try await DatabaseFolderManager.shared.dbQueue.read { db in
            try TagBean
                .filter(Column("status") == IStatusType.NORMAL.rawValue)
                .order(Column("sort").desc)
                .fetchAll(db)
        }
    }
    
    
    func upload(image: UIImage, name: String) async throws -> CloudPictureBean {
        let key = name
        // 保存图片并获取路径
        _ = ImageFileManager.saveImage(image, key)
        let pictureBean = CloudPictureBean()
        pictureBean.name = key
        let letterNum = getPinyinInitials(pictureBean.name ?? "")
        pictureBean.letterNum = letterNum
        pictureBean.duration = 0
        pictureBean.width = Int(image.size.width)
        pictureBean.height = Int(image.size.height)
        pictureBean.mimeType = "image/jpg"
        setPicture(pictureBean, key)
        return pictureBean
    }
    func upload(url: URL, name: String) async throws -> CloudPictureBean {
        // 保存图片并获取路径
        let key = VideoFileManager.saveVideo(url, name)
        let pictureBean = CloudPictureBean()
        pictureBean.name = key
        let letterNum = getPinyinInitials(pictureBean.name ?? "")
        pictureBean.letterNum = letterNum
        pictureBean.mimeType = "video/mp4"
        pictureBean.duration = 1
        pictureBean.width = 0
        pictureBean.height = 0
        setPicture(pictureBean, key)
        return pictureBean
    }
    
    private func setPicture(_ pictureBean:CloudPictureBean, _ url : String) {
        pictureBean.size = 0

        pictureBean.url = url
        pictureBean.fileId = url
        pictureBean.thumbnail = url
    }
    
    func delUrl(fileId: String) async throws {
        
    }
    
    func getUploadCapacity() -> Int {
        return 9
    }
    
    func checkCloudCapacity() -> Bool {
        return true
    }
    
    func setOften(roleId: String?) async throws {
        let config = try await getFolderConfig()
        config.aiRoleOften = roleId
        config.modifySign = true
        try await saveFolderConfig(bean: config)
    }
    
    func getOften() async throws -> String? {
        let config = try await getFolderConfig()
        return config.aiRoleOften
    }
}
